<template>
  <div class="chart-container">
    <p class="chart-title">气流温度趋势图</p>
    <div ref="chartElement" class="chart"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";

// Helper function to mirror the 3-point data into a 5-point array
// Assumes input data order: [CCT, CCT2, Edge]
// Returns output data order: [Edge, CCT2, CCT, CCT2, Edge]
function mirrorData(originalData) {
  // Basic validation: Ensure it's an array with exactly 3 elements
  if (!Array.isArray(originalData) || originalData.length !== 3) {
    console.warn("Invalid data format for mirroring. Expected array with 3 elements, received:", originalData);
    // Return a structure that ECharts can handle (e.g., nulls) to avoid errors
    return [null, null, null, null, null];
  }
  // Extract original data points assuming order: CCT, CCT2, Edge
  const data_CCT = originalData[0];
  const data_CCT2 = originalData[1];
  const data_Edge = originalData[2];

  // Construct the mirrored array: Edge, CCT2, CCT, CCT2, Edge
  return [data_Edge, data_CCT2, data_CCT, data_CCT2, data_Edge];
}

// Define the fixed mirrored x-axis labels
const mirroredXAxisLabels = ['边缘平均', 'CCT2\n（次中心）', 'CCT\n（中心温度）', 'CCT2\n（次中心）', '边缘平均'];

export default {
  name: "AirflowChart2",
  props: {
    baseCategories: {
      type: Array,
      default: () => [] // Each element expected to have { name: string, data: [cct, cct2, edge] }
    },
    currentData: {
      type: Object,
      default: () => ({ yAxisData: [] }) // Expected to have { yAxisData: [cct, cct2, edge] }
      // Note: currentData.xAxisData is now ignored
    },
    selectedLegend: {
      type: Array,
      default: () => [] // Expected to be an array of selected legend names
    }
  },
  data() {
    return {
      chartInstance: null,
      options: { // Base options structure
        toolbox: {
          show: false,
          feature: {
            dataZoom: { yAxisIndex: 'none' },
            dataView: { readOnly: true },
            saveAsImage: {}
          },
          top: '8%',
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'cross', crossStyle: { color: '#ccc', width: 1, type: 'dashed' } },
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#999',
          borderWidth: 1,
          padding: 8,
          textStyle: { color: '#333' },
          formatter: function (params) {
            // Display the correct label from the mirrored axis
            let result = params[0].axisValueLabel + '<br/>'; // Use axisValueLabel for potentially multi-line labels
            params.forEach(item => {
              result += item.marker + item.seriesName + ': ' + (item.value !== undefined && item.value !== null ? item.value + ' °C' : 'N/A') + '<br>'
            })
            return result
          },
        },
        xAxis: {
          type: 'category',
          data: mirroredXAxisLabels, // Set the fixed mirrored labels here or in updateChart
          axisLabel: {
            rotate: 0,
            interval: 0, // Show all labels
            textStyle: { fontSize: 12, color: '#333' }
          },
          axisLine: { lineStyle: { color: '#000', type: 'solid', width: 2 } },
          splitLine: { show: true, lineStyle: { color: '#ccc', type: 'solid', width: 1 } }
        },
        yAxis: {
          type: 'value',
          axisLabel: { formatter: '{value} °C' },
          axisLine: { lineStyle: { color: '#000', type: 'solid', width: 2 } },
          splitLine: { show: true, lineStyle: { color: '#ccc', type: 'solid', width: 0.5 } }
        },
        grid: {
          left: '2%',
          right: '2%',
          bottom: '2%',
          top: '12%',
          containLabel: true,
          borderColor: '#000',
          borderWidth: 1.5,
          show: true
        },
        legend: {
          type: 'scroll',
          data: [], // Will be populated dynamically
          top: '0%',
          textStyle: { fontSize: 12 },
          width: '100%',
          pageButtonItemGap: 4,
          pageButtonGap: 2,
          pageButtonPosition: 'end',
          pageIconColor: '#000',
          pageIconInactiveColor: '#aaa',
          pageTextStyle: { color: '#000', fontSize: 10 },
          selected: {} // To manage selected state dynamically
        },
        series: [], // Will be populated dynamically
        color: ['#0037fc', '#6dbcdc', '#a0c782', '#caa5ce', '#93acc4','#f8d3a3','#f8a3a3','#c8e3e3']
      }
    };
  },
  mounted() {
    this.initChart();
    window.addEventListener('resize', this.handleResize);
    this.updateChart(); // Initial update
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    this.chartInstance?.dispose();
  },
  watch: {
    baseCategories: {
      deep: true,
      handler() {
        this.updateChart();
      }
    },
    currentData: {
      deep: true,
      handler() {
        this.updateChart();
      }
    },
    selectedLegend: {
      deep: true,
      handler() {
        this.updateChart();
      }
    }
  },
  methods: {
    getLabel(str){
      const match = str.match(/[0-9A-Z]/);
      // 如果匹配成功，返回第一个匹配的字符；否则返回 null（或自定义默认值）
      return match ? match[0] : null;
    },

    initChart() {
      if (!this.$refs.chartElement) return;
      this.chartInstance = echarts.init(this.$refs.chartElement);
      // Set initial options, including the potentially pre-defined xAxis data
      this.chartInstance.setOption(this.options);

      // 监听legendselectchanged事件，当用户点击legend时更新selectedLegend
      this.chartInstance.on('legendselectchanged', (params) => {
        const selectedNames = Object.keys(params.selected).filter(name => params.selected[name]);
        this.$emit('update:selectedLegend', selectedNames);
      });
    },
    updateChart() {
      if (!this.chartInstance) return;

      const newSeries = [];
      const newLegendData = [];

      // --- Add Current Data Series ---
      const currentName = '当前气流';
      // Ensure currentData and its yAxisData exist and have the correct length (3)
      if (this.currentData && this.currentData.yAxisData && this.currentData.yAxisData.length === 3) {
        const mirroredCurrentData = mirrorData(this.currentData.yAxisData); // Apply mirroring
        newSeries.push({
          name: currentName,
          type: 'line',
          data: mirroredCurrentData, // Use mirrored data
          smooth: true,
          lineStyle: { type: 'solid' },
          itemStyle: { color: this.options.color[0] }
        });
        newLegendData.push(currentName);
      } else if (this.currentData && this.currentData.yAxisData) {
        // Log a warning if data exists but is not in the expected format
        console.warn(`Current data for '${currentName}' has incorrect length. Expected 3, got ${this.currentData.yAxisData.length}. Skipping series.`);
      }

      // --- Add Base Category Series ---
      this.baseCategories.forEach((category, index) => {
        const categoryName = this.getLabel(category.name);
        // Ensure category data exists and has the correct length (3)
        if (category.data && category.data.length === 3) {
          const mirroredBaseData = mirrorData(category.data); // Apply mirroring
          newSeries.push({
            name: categoryName,
            type: 'line',
            data: mirroredBaseData, // Use mirrored data
            smooth: true,
            lineStyle: { type: 'dashed' },
            itemStyle: { color: this.options.color[(index + 1) % this.options.color.length] }
          });
          newLegendData.push(categoryName);
        } else {
          // Log a warning if data exists but is not in the expected format
          console.warn(`Base category data for '${categoryName}' has incorrect length. Expected 3, got ${category.data?.length}. Skipping series.`);
        }
      });

      const option = this.chartInstance.getOption();
      const legendData = option.legend[0].data || [];
      const selectedState = {};
      legendData.forEach(name => {
        selectedState[name] = this.selectedLegend.includes(name);
      });
      selectedState['当前气流'] = true;


      // --- Update Options and Set ---
      this.chartInstance.setOption({
        xAxis: [{
          data: mirroredXAxisLabels // Ensure x-axis labels are set correctly
        }],
        legend: {
          data: [...new Set(newLegendData)], // Unique legend items
          selected: selectedState
        },
        series: newSeries
      }, { notMerge: false }); // notMerge ensures old series are removed if not present in newSeries

    },
    handleResize() {
      this.chartInstance?.resize();
    }
  }
};
</script>

<style scoped>
/* Styles remain the same */
.chart-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 200px; /* Ensure a minimum height */
}
.chart-title {
  text-align: center;
  margin: 2px 0; /* 减小上下边距 */
  font-size: 0.9em; /* 减小字体大小 */
  font-weight: bold;
  color: #333;
  line-height: 1.2; /* 减小行高 */
}
.chart {
  flex-grow: 1;
  width: 100%;
  height: 100%; /* Allow chart to fill the container space */
}
</style>
